import { request } from '../../request/index'
import { backUrl, fengmian } from '../../request/backImg'
Page({
    /**
     * 页面的初始数据
     */
    data: {
        userId: '',
        annualcover: true,
        authorizeStatus: false, // 用于判断是否鉴权
        phoneStatus: false, // 用于显示与隐藏获取手机号蒙层: false -> 隐藏，true -> 显示
        upData: '', // 年报详情
        playStatus: true, // 控制音乐图片转动
        txtData: [], // 每页的文字
        supportStatus: false, // 是否点赞
        shareStatus: false, // 是否分享
        loginCode: '', // 微信login返回的code,
        windowHeight: '', // 手机的高度
        windowWidth: '', // 手机的宽度
        shareImage: '', // 生成的海报图片
        showShareImg: false, // 用于显示与隐藏分享海报图片蒙层
        showShareBtn: true, // 显示隐藏分享按钮
        fengmian: '', // 海报封面图片
    },
    // 查看年报按钮
    handleDetail() {
        let authorizeStatus = wx.getStorageSync('authorizeStatus')
        let phoneStatus = wx.getStorageSync('phoneStatus')
        this.setData({ authorizeStatus, phoneStatus: false })
        // 用户已经鉴权
        if (authorizeStatus) {
            if (phoneStatus) { // 已经获取用户手机号码, 隐藏获取手机号码蒙层, 跳转年报详情
                // 获取本地保存的年报详情
                let screenList = wx.getStorageSync('screenList')
                // 保存年报详情数据
                this.setData({
                    upData: screenList
                })
                this.setData({
                    phoneStatus: false,
                    annualcover: false
                })
                this.audioContext = wx.createAudioContext('music', this);
                this.audioContext.play()

                // 默认显示第一页年报
                this.handleTxt(screenList[0].stringContent)

                // 获取保存到本地是否点赞
                let supportStatus = wx.getStorageSync('supportStatus')
                if (supportStatus == 0) { // 没有点赞
                    this.setData({ supportStatus: false })
                } else { // 已经点赞
                    this.setData({ supportStatus: true })
                }
            } else { // 未获取用户手机号码, 显示获取手机号码蒙层
                this.setData({ phoneStatus: true })
            }
        } else { // 用户未经鉴权, 显示获取手机号码蒙层
            wx.getUserProfile({
                desc: '用于完善会员资料',
                success: (res) => {
                    this.setData({ authorizeStatus: true })
                    wx.setStorageSync('userInfo', res);
                    this.setData({ phoneStatus: true })
                }
            })
        }
    },
    // 暂不授权手机号码
    handleClose() {
        this.setData({ phoneStatus: false })
    },
    // 用户未经授权手机号, 执行授权操作, 授权成功之后关闭蒙层，跳转年报详情页面
    getPhone(e) {
        let userInfo = wx.getStorageSync('userInfo');
        let _this = this;
        if (e.detail.errMsg == "getPhoneNumber:fail user deny") {
            this.setData({
                phoneStatus: false
            })
        } else {
            let encryptedData = e.detail.encryptedData, iv = e.detail.iv;
            wx.checkSession({
                success: (res) => {
                    request({
                        url: '/xcxApi/login/login',
                        method: 'get',
                        data: {
                            encryptedData,
                            iv,
                            code: _this.data.loginCode,
                            rawData: userInfo.rawData
                        }
                    }).then(res => {
                        if (!_this.data.userId) {
                            _this.setData({ userId: res.user.id });
                        }
                        wx.setStorageSync('token', res.xcxLoginToken);
                        // 获取年报详情
                        request({
                            url: '/xcxApi/yearReport/yearReportForm',
                            method: 'get',
                            data: {
                                id: _this.data.userId
                            }
                        }).then(res => {
                            // 保存接口返回的年报详情数据
                            this.setData({
                                upData: res.screenList
                            })
                            // 将年报详情保存到本地，避免重复调用查询年报接口
                            wx.setStorageSync('screenList', res.screenList)

                            //  保存授权手机号码的状态到本地，用于点击查看年报时候不重复授权
                            wx.setStorageSync('phoneStatus', true)
                            wx.setStorageSync('authorizeStatus', true)

                            // 关闭手机号码蒙层
                            this.setData({
                                phoneStatus: false,
                                annualcover: false
                            })
                            // 音乐自动播放
                            this.audioContext = wx.createAudioContext('music', this);
                            this.audioContext.play()
                            // 默认显示第一页年报
                            this.handleTxt(res.screenList[0].stringContent)

                            // 查询用户是否点赞
                            request({
                                url: '/xcxApi/yearReport/findShareYearReport',
                                method: 'get',
                                data: {
                                    vipUserId: _this.data.userId,
                                    reportYear: '2021'
                                }
                            }).then(supportStatus => {
                                // 保存是否点赞
                                wx.setStorageSync('supportStatus', supportStatus.myShare)
                                // 点赞图片状态设置
                                if (supportStatus.myShare == 0) { // 没有点赞
                                    _this.setData({ supportStatus: false })
                                } else { // 已经点赞
                                    _this.setData({ supportStatus: true })
                                }
                            })
                        })
                    })
                },
                fail: () => {
                    wx.login({
                        success: (result) => {
                            request({
                                url: '/xcxApi/login/login',
                                method: 'get',
                                data: {
                                    encryptedData,
                                    iv,
                                    code: result.code,
                                    rawData: userInfo.rawData
                                }
                            }).then(res => {
                                if (!_this.data.userId) {
                                    _this.setData({ userId: res.user.id });
                                }
                                wx.setStorageSync('token', res.xcxLoginToken);
                                // 获取年报详情
                                request({
                                    url: '/xcxApi/yearReport/yearReportForm',
                                    method: 'get',
                                    data: {
                                        id: _this.data.userId
                                    }
                                }).then(res => {
                                    // 保存接口返回的年报详情数据
                                    this.setData({
                                        upData: res.screenList
                                    })
                                    // 将年报详情保存到本地，避免重复调用查询年报接口
                                    wx.setStorageSync('screenList', res.screenList)

                                    //  保存授权手机号码的状态到本地，用于点击查看年报时候不重复授权
                                    wx.setStorageSync('phoneStatus', true)
                                    wx.setStorageSync('authorizeStatus', true)

                                    // 关闭手机号码蒙层
                                    this.setData({
                                        phoneStatus: false,
                                        annualcover: false
                                    })
                                    // 音乐自动播放
                                    this.audioContext = wx.createAudioContext('music', this);
                                    this.audioContext.play()
                                    // 默认显示第一页年报
                                    this.handleTxt(res.screenList[0].stringContent)

                                    // 查询用户是否点赞
                                    request({
                                        url: '/xcxApi/yearReport/findShareYearReport',
                                        method: 'get',
                                        data: {
                                            vipUserId: _this.data.userId,
                                            reportYear: '2021'
                                        }
                                    }).then(supportStatus => {
                                        // 保存是否点赞
                                        wx.setStorageSync('supportStatus', supportStatus.myShare)
                                        // 点赞图片状态设置
                                        if (supportStatus.myShare == 0) { // 没有点赞
                                            _this.setData({ supportStatus: false })
                                        } else { // 已经点赞
                                            _this.setData({ supportStatus: true })
                                        }
                                    })
                                })
                            })
                        },
                    });
                }
            })
        }
    },
    // 用户已经授权手机号，执行跳转年报详情操作
    toActiveDetail() {
        console.log('用户已经授权手机号，执行跳转年报详情操作');
    },
    // 音乐播放与暂停
    handlePlay() {
        this.setData({
            playStatus: !this.data.playStatus
        })
        if (this.data.playStatus) {
            this.audioContext.play()
        } else {
            this.audioContext.pause()
        }
    },
    // 年报滑动事件
    handleChane(e) {
        // 获取切换之后的页数
        let page = e.detail.current
        let upData = this.data.upData
        this.setData({ txtData: [] })
        this.handleTxt(upData[page].stringContent)
    },
    // 依次添加文字
    handleTxt(data) {

        let txt = []
        clearInterval(this.time)
        let i = 0;
        this.time = setInterval(() => {
            txt.push(data[i])
            i++;
            this.setData({
                txtData: txt
            })
            if (i >= data.length) {
                clearInterval(this.time)
            }
        }, 500);
    },
    // 点赞
    handleSupport() {
        let _this = this;
        let supportStatus = this.data.supportStatus;
        request({
            url: '/xcxApi/yearReport/praiseYearReportForm',
            method: 'get',
            data: {
                vipUserId: _this.data.userId,
                reportYear: '2021'
            }
        }).then(res => {
            if (supportStatus) {
                wx.setStorageSync('supportStatus', 0)
                wx.showToast({
                    title: '您已取消点赞！',
                    icon: 'success',
                    duration: 1500,
                    mask: true
                });
            } else {
                wx.setStorageSync('supportStatus', 1)
                wx.showToast({
                    title: '点赞成功！',
                    icon: 'success',
                    duration: 1500,
                    mask: true
                });
            }
            _this.setData({ supportStatus: !supportStatus })
        })
    },
    // 关闭分享海报图片
    closeShareImg() {
        this.setData({ showShareImg: false })
    },
    // 保存图片到手机
    saveImg() {
        wx.saveImageToPhotosAlbum({
            filePath: this.data.shareImage,
            success: (result) => {
                wx.showToast({
                    title: '海报已保存',
                    icon: 'success',
                    duration: 1000,
                    mask: true
                })
            },
            fail: () => { },
            complete: () => { }
        });

    },
    // 生成分享海报
    async handleShare() {
        let _this = this;
        // 用户id，需要作为参数，放在小程序码中
        let userId = _this.data.userId;
        console.log('userId:', userId);
        // 手机高度
        let windowHeight = _this.data.windowHeight;
        // 手机宽度
        let windowWidth = _this.data.windowWidth
        // 获取AccessToken
        let AccessToken = await request({ url: '/xcxApi/yearReport/getXcxAccessToken' })
        // 获取小程序码
        wx.request({
            url: 'https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=' + AccessToken,
            data: {
                "page": "pages/annual/annual", //默认跳转到主页:pages/index/index，可指定
                "check_path": false,
                "width": 100,
                "scene": userId,
                // "is_hyaline": true
            },
            responseType: 'arraybuffer', // 这行很重要,转为二进制数组
            arraybuffer: true,
            header: { 'content-type': 'application/json;charset=utf-8' },
            method: 'POST',
            success: res => {
                // 将buffer格式小程序码转化成base64格式
                const base64 = "data:image/png;base64," + wx.arrayBufferToBase64(res.data)
                // 将base64格式的图片保存到本地临时文件
                wx.getFileSystemManager().writeFile({
                    filePath: wx.env.USER_DATA_PATH + "/code.png",
                    data: res.data,
                    encoding: 'base64',
                    success: () => {
                        wx.showLoading({
                            title: '海报生成中',
                            mask: true
                        });
                          
                        let baseCode = wx.env.USER_DATA_PATH + "/code.png"
                        // 下载背景图片到本地
                        wx.getImageInfo({
                            src: backUrl,
                            success: bgRes => {
                                // 保存背景图片为本地地址
                                let backgroundImage = bgRes.path
                                // 绘制海报
                                const ctx = wx.createCanvasContext('shareCanvas')
                                // 海报背景图片
                                ctx.drawImage(backgroundImage, 0, 0, windowWidth, windowHeight)
                                // ctx.setTextAlign('center')
                                // ctx.setFillStyle('#f00')
                                // ctx.setFontSize(22)
                                // ctx.fillText('请保存图片分享到朋友圈！', 185, 200)
                                // 小程序码
                                ctx.drawImage(baseCode, (windowWidth - 100) / 2, windowHeight - 120, 100, 100)
                                ctx.stroke()
                                ctx.draw(false, () => {
                                    // 将绘制的海报保存成图片
                                    wx.canvasToTempFilePath({
                                        canvasId: 'shareCanvas',
                                        x: 0,
                                        y: 0,
                                        width: windowWidth,
                                        height: windowHeight,
                                        destWidth: windowWidth,
                                        destHeight: windowHeight,
                                        success: canvasImage => {
                                            let canvasToTempFilePath = canvasImage.tempFilePath
                                            _this.setData({
                                                shareImage: canvasToTempFilePath,
                                                showShareImg: true
                                            })
                                            wx.hideLoading();
                                            wx.showToast({
                                                title: '生成海报成功',
                                                icon: 'success',
                                                duration: 1000,
                                                mask: true
                                            })
                                        },
                                        fail: () => {
                                            wx.showToast({
                                                title: '生成海报失败',
                                                icon: 'error',
                                                duration: 1000,
                                                mask: true
                                            })
                                        }
                                    })
                                })
                            },
                            fail: error => {
                                wx.showToast({
                                    title: '生成海报失败',
                                    icon: 'error',
                                    duration: 1000,
                                    mask: true
                                })
                            }
                        })
                    },
                    fail: () => {
                        wx.showToast({
                            title: '生成海报失败',
                            icon: 'error',
                            duration: 1000,
                            mask: true
                        })
                    }
                })
            },
            fail: error => {
                wx.showToast({
                    title: '生成海报失败',
                    icon: 'error',
                    duration: 1000,
                    mask: true
                })
            }
        })
    },
    // 关闭分享海报
    handleCloseShare() {
        this.setData({
            shareStatus: false
        })
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (option) {
        console.log('年报页面：', option);

        let userId;
        let _this = this;
        // 用于线上获取userId
        if (option.scene) {
            userId = decodeURIComponent(option.scene);
            this.setData({ userId, showShareBtn: false, fengmian });
        } 
        // 用于测试获取userId
        // this.setData({ userId: option.userId });
        wx.hideHomeButton();

        // 页面初始化的时候登录
        wx.login({
            success: res => {
                _this.setData({ loginCode: res.code })
            }
        })

        // 页面初始化的时候，获取手机的宽和高
        wx.getSystemInfo({
            success: getSystemInfo => {
                if (getSystemInfo.errMsg == "getSystemInfo:ok") {
                    // 获取手机宽度和高度
                    let windowHeight = getSystemInfo.windowHeight,
                        windowWidth = getSystemInfo.windowWidth;
                    _this.setData({ windowHeight, windowWidth })

                }
            }
        })

    }
})